<script setup>
import {Delete, Edit} from '@element-plus/icons-vue'
import {onMounted, ref} from 'vue'
import {getArticleByIdAPI, getArticleListAPI, getCategoryAPI, updateArticleByIdAPI} from "@/api/article.js";
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {useTokenStore} from "@/stores/token.js"
import {formatDate} from "@/utils/formatDate.js";
import {MdEditor} from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import {ElMessage} from "element-plus";

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  limit.value = size
  getArticleList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  page.value = num
  getArticleList()
}

const tokenStore = useTokenStore()
/**
 * 文章封面上传成功的回调
 * @param articleState
 * @returns {Promise<void>}
 */
// const uploadSuccess = (result) => {
//   articleModel.value.coverImg = result.data
// }
// const addArticle = async (articleState) => {
//   articleModel.value.state = articleState
//   const result = await articleAddService(articleModel.value)
//   alert(result.msg ? result.msg : '添加成功')
//   visibleDrawer.value = false
//   articleList()
// }
// 页码
const page = ref(1)
// 每页条数
const limit = ref(10)
// 文章分类id
const categoryId = ref(-1)
// 文章关键词
const keyword = ref('')
// 文章详情信息
const articleList = ref([])
// 文章总数
const total = ref(0)
/**
 * 分页获取文章列表
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
const getArticleList = async () => {
  const params = {
    page: page.value,
    limit: limit.value,
    keyword: keyword.value,
    categoryId: categoryId.value
  }
  const result = await getArticleListAPI(params)
  articleList.value = result.data.data.rows
  total.value = result.data.data.total
  console.log(articleList.value, total.value)
}
// 文章分类
const categoryList = ref([])
/**
 * 获取文章分类
 * @returns {Promise<void>}
 */
const getCategory = async () => {
  const result = await getCategoryAPI()
  categoryList.value = result.data.data
}
// 控制抽屉是否显示
const visibleDrawer = ref(false)
// 单篇文章信息详情
const articleModel = ref({
  id: 0,
  title: '',
  description: '',
  toc: [],
  htmlContent: "",
  thumb: "",
  scanNumber: 0,
  commentNumber: 0,
  createDate: "",
  categoryId: 1,
  category: {
    id: 1,
    name: 'html',
    articleCount: 0,
    order: 0
  }
})
/**
 * 编辑文章
 */
const editArticle = (id) => {
  visibleDrawer.value = true
  getArticleById(id)
}
/**
 * 根据文章 id 获取单篇文章
 * @param id
 * @returns {Promise<void>}
 */
const getArticleById = async (id) => {
  const result = await getArticleByIdAPI(id)
  articleModel.value = result.data.data
}
/**
 * 更新文章
 * @param id 文章id
 * @param body 文章数据
 * @returns {Promise<void>}
 */
const updateArticle = async (id, body) => {
  const result = await updateArticleByIdAPI(id, body)
  console.log(result)
  result.data?.code === 0 ? ElMessage.success("更新成功") : ElMessage.warning(result?.msg)
  await getArticleList()
  visibleDrawer.value = false
}
onMounted(() => {
  getArticleList()
  getCategory()
})
</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>活动管理</span>
        <div class="extra">
          <el-button type="primary" @click="visibleDrawer=true">添加活动</el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="活动分类：">
        <el-select placeholder="请选择" v-model="categoryId">
<!--          todo: 解决分类为 -1 是没有友好提示的 bug-->
          <el-option
              v-for="c in categoryList"
              :key="c.id"
              :label="c.name"
              :value="c.id">
          </el-option>
        </el-select>
      </el-form-item>
<!--      搜索 重置-->
      <el-form-item>
        <el-button type="primary" @click="getArticleList">搜索</el-button>
        <el-button @click="categoryId=-1;getArticleList()">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table border :data="articleList" style="width: 100%" :default-sort="{ prop: 'createDate', order: 'descending' }">
      <el-table-column label="序号"  align="center" width="100" type="index"></el-table-column>
      <el-table-column label="活动标题" align="center" width="200" prop="title"></el-table-column>
      <el-table-column label="浏览数" align="center" prop="scanNumber"></el-table-column>
      <el-table-column label="评论数" align="center" prop="commentNumber"></el-table-column>
      <el-table-column label="所属分类" align="center">
        <template #default="{ row }">
          {{ row.category.name }}
        </template>
      </el-table-column>
      <el-table-column label="创建日期" align="center" sortable prop="createDate" >
        <template #default="{row}">
          {{ formatDate(row.createDate) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button @click="editArticle(row.id)" :icon="Edit" circle plain type="primary"></el-button>
          <el-button :icon="Delete" circle plain type="danger"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据"/>
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="page" v-model:page-size="limit" :page-sizes="[3, 5 ,10, 15]"
                   layout="jumper, total, sizes, prev, pager, next" background :total="total"
                   @size-change="onSizeChange"
                   @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end"/>
    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" title="更新活动" direction="rtl" size="100%">
      <!-- 添加文章表单 -->
      <el-form :model="articleModel">
        <el-form-item label="活动标题">
          <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="活动描述">
          <el-input v-model="articleModel.description" placeholder="请输入活动描述"></el-input>
        </el-form-item>
        <el-form-item label="活动内容">
          <div class="editor">
            <MdEditor v-model="articleModel.htmlContent" />
          </div>
        </el-form-item>
        <el-form-item label="活动分类">
          <el-select placeholder="请选择" v-model="articleModel.categoryId">
            <!--  todo: 解决分类为 -1 是没有友好提示的 bug-->
            <el-option
                v-for="c in categoryList"
                :key="c.id"
                :label="c.name"
                :value="c.id">
            </el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="文章封面">-->
<!--          <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="true"-->
<!--                     action="/api/upload"-->
<!--                     name="file"-->
<!--                     :headers="{'Authorization':tokenStore.token}"-->
<!--                     :on-success="uploadSuccess"-->
<!--          >-->
<!--            <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" alt=""/>-->
<!--            <el-icon v-else class="avatar-uploader-icon">-->
<!--              <Plus/>-->
<!--            </el-icon>-->
<!--          </el-upload>-->
<!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="updateArticle(articleModel.id, articleModel)">更新</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-card>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

/* 抽屉样式 */
.avatar-uploader {
  :deep(.avatar) {
    width: 178px;
    height: 178px;
    display: block;
  }

  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }

  :deep(.el-icon.avatar-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }

}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>